package com.baoxin.chenxixc4coach;

import android.app.TimePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.baoxin.chenxixc4coach.bean.AdvanceCourse;
import com.baoxin.chenxixc4coach.utils.DensityUtil;
import com.baoxin.chenxixc4coach.utils.ListSaveUtils;
import com.baoxin.chenxixc4coach.utils.TimeUtil;

import java.util.ArrayList;
import java.util.Date;

import static com.baoxin.chenxixc4coach.CourseSettingActivity.ADVANCE_MOULD_NAME;

public class AdvanceMouldActivity extends BaseActivity {

    private LinearLayout courseLL;
    private ArrayList<AdvanceCourse> advanceCourseList;
    private Button bottomView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_advance_mould);
        courseLL = findViewById(R.id.course_ll);
        initCourseViewBySave();

        LinearLayout rootView = findViewById(R.id.root_view);
        bottomView = findViewById(R.id.use_mould);

        rootView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                if (oldBottom - bottom > 1) {//布局发生变化，底部上去了（软键盘弹出）//软键盘弹上去了,动态设置高度为0
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0);
                    bottomView.setLayoutParams(params);
                } else if (oldBottom - bottom < -1) {//软键盘弹下去
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                            DensityUtil.dp2px(AdvanceMouldActivity.this, 48f));
                    bottomView.setLayoutParams(params);
                }
            }
        });
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    //存在本地的数据数量
    int sizeOfSave;
    int indexOfSave = 0;

    private void initCourseViewBySave() {
        advanceCourseList = ListSaveUtils.getDataEntities(ADVANCE_MOULD_NAME);
        sizeOfSave = advanceCourseList.size();
        for (int i = 0; i < sizeOfSave; i++) {
            onAddCourse(null);
        }
    }

    public void onAddCourse(View view) {
        LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        params1.topMargin = 45;//px
        LinearLayout linearLayout = createCourseView();

        courseLL.addView(linearLayout, params1);
    }

    /**
     * 创建课程view
     *
     * @return
     */
    private LinearLayout createCourseView() {
        final LinearLayout courseView = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.single_course, null);

        TextView mStartTime = courseView.findViewById(R.id.start_time);
        TextView mEndTime = courseView.findViewById(R.id.end_time);
        EditText mNumber = courseView.findViewById(R.id.number);
        EditText mPrice = courseView.findViewById(R.id.price);
        ImageView mDelete = courseView.findViewById(R.id.delete);

        if (indexOfSave < sizeOfSave) {
            AdvanceCourse advanceCourse = advanceCourseList.get(indexOfSave);
            mStartTime.setText(advanceCourse.startStr);
            mEndTime.setText(advanceCourse.endStr);
            mNumber.setText("" + advanceCourse.number);
            mPrice.setText("" + advanceCourse.price);
            indexOfSave++;
        }
        mStartTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                TimePickerDialog timePickerDialog = new TimePickerDialog(AdvanceMouldActivity.this,
                        new TimePickerDialog.OnTimeSetListener() {
                            @Override
                            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                                StringBuilder sb = new StringBuilder();
                                if (hourOfDay > 9) {
                                    sb.append(hourOfDay);
                                } else {
                                    sb.append("0").append(hourOfDay);
                                }
                                sb.append(":");
                                if (minute > 9) {
                                    sb.append(minute);
                                } else {
                                    sb.append("0").append(minute);
                                }
                                ((TextView) v).setText(sb);
                            }
                        }, 8, 0, true);
                timePickerDialog.show();
            }
        });

        mEndTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                TimePickerDialog timePickerDialog = new TimePickerDialog(AdvanceMouldActivity.this,
                        new TimePickerDialog.OnTimeSetListener() {
                            @Override
                            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                                StringBuilder sb = new StringBuilder();
                                if (hourOfDay > 9) {
                                    sb.append(hourOfDay);
                                } else {
                                    sb.append("0").append(hourOfDay);
                                }
                                sb.append(":");
                                if (minute > 9) {
                                    sb.append(minute);
                                } else {
                                    sb.append("0").append(minute);
                                }
                                ((TextView) v).setText(sb);
                            }
                        }, 8, 0, true);
                timePickerDialog.show();
            }
        });

        mDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                courseLL.removeView(courseView);
            }
        });
        return courseView;
    }

    private boolean pass() {
        int courseSize = courseLL.getChildCount();
        if (courseSize == 0) {
            Toast.makeText(this, "未设置课程！", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (isIllegal()) {
            Toast.makeText(this, "课程设置有误！", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * advanceCourseList先储存课程,再检测课程时间是否合理
     */
    private boolean isIllegal() {

        int courseSize = courseLL.getChildCount();
        advanceCourseList = new ArrayList<>(courseSize);
        for (int i = 0; i < courseSize; i++) {
            LinearLayout linearLayout = (LinearLayout) courseLL.getChildAt(i);
            TextView startTime = linearLayout.findViewById(R.id.start_time);
            TextView endTime = linearLayout.findViewById(R.id.end_time);
            EditText mNumber = linearLayout.findViewById(R.id.number);
            EditText mPrice = linearLayout.findViewById(R.id.price);

            Date startDate = TimeUtil.StrToDate("1970/1/1" + " " + startTime.getText().toString(), "yyyy/MM/dd HH:mm");
            Date endDate = TimeUtil.StrToDate("1970/1/1" + " " + endTime.getText().toString(), "yyyy/MM/dd HH:mm");

            AdvanceCourse h = new AdvanceCourse(startDate, endDate);
            h.startStr = startTime.getText().toString();
            h.endStr = endTime.getText().toString();
            h.number = Integer.parseInt(mNumber.getText().toString());
            h.price = Integer.parseInt(mPrice.getText().toString());

            advanceCourseList.add(h);
        }

        for (int i = 0; i < courseSize; i++) {
            AdvanceCourse h = advanceCourseList.get(i);
            if (h.start.getTime() >= h.end.getTime()) {
                return true;
            }
            for (int j = 0 + 1 + i; j < courseSize; j++) {
                AdvanceCourse h2 = advanceCourseList.get(j);
                if (isConflict(h.start, h.end, h2.start, h2.end)) {
                    return true;
                }
            }
        }
        return false;

    }

    /**
     * 判断2个课程之间是否有冲突
     *
     * @param start
     * @param end
     * @param start1
     * @param end1
     * @return
     */
    private boolean isConflict(Date start, Date end, Date start1, Date end1) {

        if (start.getTime() > start1.getTime() && start.getTime() < end1.getTime()) {
            return true;
        } else if (end.getTime() > start1.getTime() && end.getTime() < end1.getTime()) {
            return true;
        } else if (start.getTime() == start1.getTime() && end.getTime() == end1.getTime()) {
            return true;
        } else if (start1.getTime() > start.getTime() && start1.getTime() < end.getTime()) {
            return true;
        } else if (end1.getTime() > start.getTime() && end1.getTime() < end.getTime()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 保存时间设置
     *
     * @param view
     */
    public void onSave(View view) {
        if (!pass()) {
            return;
        }

        if (ListSaveUtils.saveDataList2SDCard(advanceCourseList, ADVANCE_MOULD_NAME)) {
            Toast.makeText(this, "保存成功!", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "保存失败!", Toast.LENGTH_SHORT).show();
        }

    }

    public void onUseMould(View view) {
        onSave(null);
        setResult(1);
        finish();
    }
}
